package com.lxx.train.gateway.config;

import org.springframework.context.annotation.Bean;  
import org.springframework.context.annotation.Configuration;  
import org.springframework.web.cors.CorsConfiguration;  
import org.springframework.web.cors.reactive.CorsWebFilter;  
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;  
import org.springframework.web.util.pattern.PathPatternParser;  
import java.util.Arrays;  

@Configuration
public class CorsConfig {  
    
    @Bean  
    public CorsWebFilter corsFilter() {  
        CorsConfiguration config = new CorsConfiguration();  
        
        // 允许的源  
        config.setAllowedOriginPatterns(Arrays.asList("*"));  
        // 或指定具体源  
        // config.setAllowedOrigins(Arrays.asList(  
        //     "http://localhost:8080",  
        //     "http://localhost:3000",  
        //     "https://www.example.com"  
        // ));  
        
        // 允许的请求方法  
        config.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));  
        
        // 允许的请求头  
        config.setAllowedHeaders(Arrays.asList("*"));  
        
        // 允许携带认证信息  
        config.setAllowCredentials(true);  
        
        // 暴露的响应头  
        config.setExposedHeaders(Arrays.asList(  
            "Authorization",  
            "Content-Type",  
            "X-Total-Count",  
            "X-Custom-Header"  
        ));  
        
        // 预检请求缓存时间  
        config.setMaxAge(3600L);  
        
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser());  
        source.registerCorsConfiguration("/**", config);  
        
        return new CorsWebFilter(source);  
    }  
} 